
const dateJs = require("date.js");
import {
  getinviteKey,
  getToken
} from "../../utils/storage";
const CN_Date = require("getCNDate.js");
const t = new Date();
import {
  typeToMap
} from "../../config";
import {
  formatNoZeroDate
} from "../../utils/date";

import {
  getScheduleDataList,
  getScheduleInfo
} from "../../api/calendar";
Page({
  data: {
    //计算红点出现的月份
    count: 0,
    calendarHeight: "",
    changeHight: "",
    animationShow: false,
    animationData: {},
    monthNum: t.getMonth() + 1,
    yearNum: t.getFullYear(),
    MonthDayArray: [],
    toDate: t.getDate(),
    toMonth: t.getMonth() + 1,
    toYear: t.getFullYear(),
    fromToday: "今天",
    nongliDetail: CN_Date(t.getFullYear(), t.getMonth() + 1, t.getDate()),
    dayList: [],
    //用于数据传输
    tempdayList: [],
    //全部的日期
    alldayList: [],
    // isShowPoint:true
    holidays: [{
        "01-01": "元旦",
      },
      {
        "02-14": "情人节",
      },
      {
        "03-08": "妇女节",
      },
      {
        "03-12": "植树节",
      },
      {
        "03-15": "消费者权益日",
      },
      {
        "04-01": "愚人节",
      },
      {
        "05-01": "劳动节",
      },
      {
        "05-04": "青年节",
      },
      {
        "05-12": "护士节",
      },
      {
        "06-01": "儿童节",
      },
      {
        "07-01": "建党节",
      },
      {
        "08-01": "建军节",
      },
      {
        "09-10": "教师节",
      },
      {
        "09-28": "孔子诞辰",
      },
      {
        "10-01": "国庆节",
      },
      {
        "10-06": "老人节",
      },
      {
        "10-24": "联合国日",
      },
      {
        "12-24": "平安夜",
      },
      {
        "12-25": "圣诞节",
      },
    ],
    lunarholidays: [{
        正月初一: "春节",
      },
      {
        正月十五: "元宵节",
      },
      {
        五月初五: "端午节",
      },
      {
        七月初七: "七夕",
      },
      {
        七月十五: "中元节",
      },
      {
        八月十五: "中秋节",
      },
      {
        九月初九: "重阳节",
      },
      {
        腊月初八: "腊八节",
      },
      {
        腊月廿四: "小年",
      },
    ],
    allMonthDayList: [],
    boxheigth: ""
  },
  onLoad: function () {},
  onShow: function () {
 

    let that = this
    this.calcMonthDayArray();
 

    let today = formatNoZeroDate(
      `${t.getFullYear()}-${t.getMonth() + 1}-${t.getDate()}`
    );
    if (getToken()) {
      this.setScheduleDataList(today);
      this.setScheduleInfo();      
    }


    let query = wx.createSelectorQuery();
    query
      .select(".monthDay")
      .boundingClientRect((rect) => {
        let clientHeight = rect.height;
        let clientWidth = rect.width;
        let ratio = 750 / clientWidth;
        let height = clientHeight * ratio;
 
        that.setData({
          boxheigth: height
        })
  
        let changeHeight = this.data.calendarHeight - height;
 
        if (height < 580) {
          // this.animation(changeHeight)
 

          const animation = wx.createAnimation({
            // transformOrigin: "50% 50%",
            delay: 0,
            duration: 1000,
            timingFunction: "ease",
          });
          this.animation = animation;

          animation.translateY(-50).step();

          // if(e < 0) {
          //   animation.translateY(0).step();
          // }
          this.setData({
            animationData: animation.export(),
          });
        } else {
          const animation = wx.createAnimation({
   
            delay: 0,
            duration: 1000,
            timingFunction: "ease",
          });
          this.animation = animation;

          animation.translateY(0).step();

     
          this.setData({
            animationData: animation.export(),
          });
        }

        this.setData({
          calendarHeight: height,
          changeHight: changeHeight,
        });
      })
      .exec();
  },
  //跳转到我的test
  gotomine() {
    wx.navigateTo({
      url: "/pages/calendar/personalDetail/p",
    });
  },
  //判断农历节日
  lunarevent(lunarholiday, thedayon) {
 
    for (let i = 0; i < this.data.lunarholidays.length; i++) {
      if (Object.keys(this.data.lunarholidays[i])[0] == lunarholiday) {
        thedayon.nongli = Object.values(this.data.lunarholidays[i]);
        thedayon.nonglishow = true;
 
      } else {}
    }
  },
  //判断节日
  holidayevent(everyholiday, thedayon, lunarholiday) {
    for (let i = 0; i < this.data.holidays.length; i++) {
 
      if (Object.keys(this.data.holidays[i])[0] == everyholiday) {
 
        thedayon.nongli = Object.values(this.data.holidays[i]);
  
      }
    }
  },
  //编辑信息
  gotoedit(e) {
     
    let that = this;
    // let target = that.data.dayList[e]
    wx.navigateTo({
      url: "/pages/calendar/editSchedule/editSchdule",
      events: {
        editDate: function (data) {
           
        },
      },
      success: function (res) {
        res.eventChannel.emit(
          "editDate",
          that.data.dayList[e.currentTarget.dataset.index]
        );
      },
    });
  },
  //跳转页面我的
  gotoMy() {
    let that = this;
    wx.navigateTo({
      url: "/pages/calendar/createSchedule/createSchedule?id=1",
      events: {
        //设置监听函数
        currentDate: function (data) {
           
        },
      },
      success: function (res) {
        res.eventChannel.emit("currentDate", {
          year: that.data.toYear,
          month: that.data.toMonth,
          day: that.data.toDate,
          lunar: that.data.nongliDetail,
        });
      },
    });
  },
  gotoCheck() {
    let that = this;
    wx.navigateTo({
      url: "/pages/calendar/checkSchedule/checkSchedule",
      events: {
        //设置监听函数
        currentDate: function (data) {
           
        },
      },
      success: function (res) {
        res.eventChannel.emit("currentDate", {
          year: that.data.toYear,
          month: that.data.toMonth,
          day: that.data.toDate,
          lunar: that.data.nongliDetail,
        });
      },
    });
  },
  dateClick: function (e) {
    const eId = e.currentTarget.id;
    const MonArray = this.data.MonthDayArray;
    const data = this.data;
     
 
    if (eId == "") return;
    //点击效果 ，且只能选中一个日期
    //FIX 这个遍历算法可以改进
    for (let i = 0; i < MonArray.length; i++) {
      for (let j = 0; j < MonArray[i].length; j++) {
        if (typeof MonArray[i][j] == "string") {
          continue;
        }
        if (MonArray[i][j].num == eId) {
          MonArray[i][j].isShowDayInfo = !MonArray[i][j].isShowDayInfo;
        }
      }
    }

    for (let i = 0; i < MonArray.length; i++) {
      for (let j = 0; j < MonArray[i].length; j++) {
        if (typeof MonArray[i][j] == "string" || MonArray[i][j].num == eId) {
          continue;
        }
        MonArray[i][j].isShowDayInfo = false;
      }
    }
    this.setData({
      MonthDayArray: MonArray,
      toYear: data.yearNum,
      toMonth: data.monthNum,
      toDate: eId,
      fromToday: dateJs.getFromTodayDays(eId, data.monthNum - 1, data.yearNum),
      nongliDetail: CN_Date(data.yearNum, data.monthNum, eId),
    });
    let today = formatNoZeroDate(
      `${data.yearNum}-${data.monthNum}-${data.toDate}`
    );
 
    if (getToken()) {
      this.setScheduleDataList(today);    
    }

  },

  monthTouch: function (e) {
    const beginX = e.target.offsetLeft;
 
    const endX = e.changedTouches[0].clientX;
    ;
    if (beginX - endX > 125) {
      this.nextMonth_Fn();
    } else if (beginX - endX < -125) {
      this.lastMonth_Fn();
    }
  },

  nextMonth_Fn: function () {
    const n = this.data.monthNum;
    const y = this.data.yearNum;

    if (n == 12) {
      this.setData({
        monthNum: 1,
        yearNum: y + 1,
      });
    } else {
      this.setData({
        monthNum: n + 1,
      });
    }
    this.calcMonthDayArray();
    // this.setScheduleInfo()
    this.setActiveMonth();
    let query = wx.createSelectorQuery();
    query
      .select(".monthDay")
      .boundingClientRect((rect) => {
        let clientHeight = rect.height;
        let clientWidth = rect.width;
        let ratio = 750 / clientWidth;
        let height = clientHeight * ratio;
        ;
        // ;
        let changeHeight = this.data.calendarHeight - height;
        // ;
        if (changeHeight >= 0) {
          // this.animation(changeHeight)
          const animation = wx.createAnimation({
            // transformOrigin: "50% 50%",
            delay: 0,
            duration: 1000,
            timingFunction: "ease",
          });
          this.animation = animation;

          animation.translateY(-50).step();

          // if(e < 0) {
          //   animation.translateY(0).step();
          // }
          this.setData({
            animationData: animation.export(),
          });
        } else {
          const animation = wx.createAnimation({
            // transformOrigin: "50% 50%",
            delay: 0,
            duration: 1000,
            timingFunction: "ease",
          });
          this.animation = animation;

          animation.translateY(0).step();

          // if(e < 0) {
          //   animation.translateY(0).step();
          // }
          this.setData({
            animationData: animation.export(),
          });
        }

        this.setData({
          calendarHeight: height,
          changeHight: changeHeight,
        });
      })
      .exec();
  },

  lastMonth_Fn: function () {
    const n = this.data.monthNum;
    const y = this.data.yearNum;
    let that = this;
    if (n == 1) {
      this.setData({
        monthNum: 12,
        yearNum: y - 1,
      });
    } else {
      this.setData({
        monthNum: n - 1,
      });
    }
    this.calcMonthDayArray();
    // this.setScheduleInfo()
    this.setActiveMonth();
    let query = wx.createSelectorQuery();
    query
      .select(".monthDay")
      .boundingClientRect((rect) => {
        let clientHeight = rect.height;
        let clientWidth = rect.width;
        let ratio = 750 / clientWidth;
        let height = clientHeight * ratio;
        // ;
        ;
        let changeHeight = this.data.calendarHeight - height;
        if (changeHeight >= 0) {
          // this.animation(changeHeight)
          const animation = wx.createAnimation({
            // transformOrigin: "50% 50%",
            delay: 0,
            duration: 1000,
            timingFunction: "ease",
          });
          this.animation = animation;

          animation.translateY(-50).step();

          // if(e < 0) {
          //   animation.translateY(0).step();
          // }
          this.setData({
            animationData: animation.export(),
          });
        } else {
          const animation = wx.createAnimation({
            // transformOrigin: "50% 50%",
            delay: 0,
            duration: 1000,
            timingFunction: "ease",
          });
          this.animation = animation;

          animation.translateY(0).step();

          // if(e < 0) {
          //   animation.translateY(0).step();
          // }
          this.setData({
            animationData: animation.export(),
          });
        }

        this.setData({
          calendarHeight: height,
          changeHight: changeHeight,
        });
      })
      .exec();
  },

  calcMonthDayArray() {
    const data = this.data;
    const dateArray = dateJs.paintCalendarArray(data.monthNum, data.yearNum);
    // ;
     
    //如果不是当年当月，自动选中1号
    const notToday =
      data.monthNum != t.getMonth() + 1 || data.yearNum != t.getFullYear();
    if (notToday) {
      for (let i = 0; i < dateArray[0].length; i++) {
        if (dateArray[0][i].num == 1) {
          dateArray[0][i].isShowDayInfo = true;
        }
      }
      let data = this.data;
      let certainday = formatNoZeroDate(`${data.yearNum}-${data.monthNum}-1`);
      if (getToken()) {
        this.setScheduleDataList(certainday);
      }

    } else {
      let today = formatNoZeroDate(
        `${t.getFullYear()}-${t.getMonth() + 1}-${t.getDate()}`
      );
      ;
      if (getToken()) {
        this.setScheduleDataList(today);
      }      

    }
    // this.onShow()
    // this.onLoad()
    this.setData({
      MonthDayArray: dateArray,
      toYear: notToday ? this.data.yearNum : t.getFullYear(),
      toMonth: notToday ? this.data.monthNum : t.getMonth() + 1,
      toDate: notToday ? 1 : t.getDate(),
      fromToday: notToday ?
        dateJs.getFromTodayDays(1, data.monthNum - 1, data.yearNum) :
        "今天",
      nongliDetail: notToday ?
        CN_Date(data.yearNum, data.monthNum, 1) :
        CN_Date(t.getFullYear(), t.getMonth() + 1, t.getDate()),
    });
  },
  setScheduleDataList(date) {
    getScheduleDataList({
      date,
    }).then((res) => {
       
      let newarr = res.data.list;
      for (let i = 0; i < newarr.length; i++) {
        ;
        let newarr1 = newarr[i].time_interval.split(",");
        newarr[i].time_interval1 = newarr1[0];
        newarr[i].time_interval2 = newarr1[1];
        newarr[i].type1 = typeToMap(newarr[i].type);
      }
      this.setData({
        dayList: newarr,
        tempdayList: res.data.list,
      });
    });
  },
  setScheduleInfo() {
    getScheduleInfo({
      userId: "",
    }).then((res) => {
       
      this.setData({
        allMonthDayList: res.data.list,
      });
      // let alldate = res.data.list[0].dataList
      this.setActiveMonth();
    });
  },
  setActiveMonth() {
    let nowAllDayList = this.data.allMonthDayList.find(
      (item) =>
      item.date ===
      formatNoZeroDate(`${this.data.yearNum}-${this.data.monthNum}`)
    );
    let alldate = nowAllDayList ? nowAllDayList.dataList : [];
    ;
    this.setData({
      alldayList: alldate,
    });

    //判断红点出现的位置
    const MonArray = this.data.MonthDayArray;
    // ;
    const data = this.data;

    for (let i = 0; i < MonArray.length; i++) {
      for (let j = 0; j < MonArray[i].length; j++) {
        if (typeof MonArray[i][j] == "string") {
          continue;
        }
        let thedayon = MonArray[i][j];
        ;
        let everyday = formatNoZeroDate(
          `${data.yearNum}-${data.monthNum}-${thedayon.num}`
        );
        let everyholiday = formatNoZeroDate(`${data.monthNum}-${thedayon.num}`);
        let lunarholiday = thedayon.nongliInfo.substring(7);

        for (let z = 0; z < this.data.alldayList.length; z++) {
          if (this.data.alldayList[z].date == everyday) {
            thedayon.isShowPoint = true;
          }
        }
        this.holidayevent(everyholiday, thedayon);
        this.lunarevent(lunarholiday, thedayon);

        this.setData({
          MonthDayArray: MonArray,
        });
      }
    }
  },
});